<template>
  <header class="header">
    <a href="/">
    <div class="logo">

      <img src="https://static.zibovip.top/imgs/2025/06/176b211df0513014.jpg" alt="logo" />
      <span>商城</span>
    </div>
    </a>
    <div class="search-bar">
      <input v-model="keyword" type="text" placeholder="输入你想查找的商品" />
      <button @click="onSearch">
        <span class="icon-search"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <circle cx="11" cy="11" r="8" />
          <line x1="21" y1="21" x2="16.65" y2="16.65" />
        </svg></span>搜索
      </button>
    </div>
    <div class="auth-buttons">
      <!-- 未登录状态 -->
      <template v-if="!userStore.user">
        <button class="login" @click="goLogin">登录</button>
        <button class="register" @click="goRegister">注册</button>
      </template>
      <!-- 已登录状态 -->
      <template v-else>
        <div class="user-info" style="position:relative;">
          <span class="welcome">你好,{{ userStore.nickname || userStore.user.nickname || userStore.user.username }}</span>
          <img
            class="user-avatar"
            :src="userStore.user.avator || userStore.user.avatar || 'https://static.zibovip.top/imgs/2025/03/7139cadfe5ccf3b6.png'"
            alt="avatar"
            @click="toggleMenu"
            style="width:36px;height:36px;border-radius:50%;margin-left:12px;cursor:pointer;object-fit:cover;vertical-align:middle;"
          />
          <div v-if="showMenu" class="dropdown-menu">
            <div class="menu-item" @click="goUserCenter">个人中心</div>
            <div v-if="userStore.user && userStore.user.id === 1" class="menu-item" @click="goAdmin">后台管理</div>
            <div class="menu-item" @click="handleLogout">退出登录</div>
          </div>
        </div>
      </template>
    </div>
    <CartIcon />
  </header>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import CartIcon from './CartIcon.vue'
import { useUserStore } from '../store/user'

const keyword = ref('')
const router = useRouter()
const userStore = useUserStore()
const showMenu = ref(false)

onMounted(() => {
  // 页面加载时从本地存储初始化用户数据
  userStore.initFromStorage()
  document.addEventListener('click', handleClickOutside)
})

// watch(() => userStore.token, async (newToken) => {
//   if (newToken && userStore.user && userStore.user.id) {
//     const res = await getUserInfo(userStore.user.id)
//     if (res && res.code === 200 && res.data) {
//       userStore.setUser(res.data)
//     }
//   }
// })

function onSearch() {
  if (keyword.value) router.push({ path: '/products', query: { name: keyword.value } })
}

function goLogin() {
  router.push('/login')
  setTimeout(() => {
    window.location.reload()
  }, 100)

}

function goRegister() {
  router.push('/register')
  setTimeout(() => {
    window.location.reload()
  }, 100)
}

function handleLogout() {
  userStore.logout()
  if (router.currentRoute.value.path === '/') {
    window.location.reload()
  } else {
    router.push('/')
  }
}

function goUserCenter() {
  router.push('/user')
  // setTimeout(() => {
  //   window.location.reload()
  // }, 100)
}

function toggleMenu() {
  showMenu.value = !showMenu.value
}

function goAdmin() {
  showMenu.value = false
  router.push('/admin')
}

// 点击外部关闭下拉
function handleClickOutside(event: MouseEvent) {
  const menu = document.querySelector('.dropdown-menu')
  const avatar = document.querySelector('.user-avatar')
  if (menu && !menu.contains(event.target as Node) && avatar && !avatar.contains(event.target as Node)) {
    showMenu.value = false
  }
}

onMounted(() => {
  userStore.initFromStorage()
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 40px;
  background: linear-gradient(135deg, #ffffff, #f8fafc);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
  transition: background 0.3s ease;
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 24px;
  font-weight: 700;
  color: #1e40af;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.logo img {
  width: 40px;
  height: 40px;
  object-fit: contain;
  transition: transform 0.3s ease;
}

.logo:hover img {
  transform: scale(1.1);
}

.logo span {
  letter-spacing: 1px;
  background: linear-gradient(to right, #1e40af, #3b82f6);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.search-bar {
  flex: 1;
  max-width: 600px;
  margin: 0 48px;
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s ease;
}

.search-bar:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.search-bar input {
  flex: 1;
  padding: 12px 16px;
  border: none;
  outline: none;
  font-size: 16px;
  color: #333;
  background: transparent;
}

.search-bar input::placeholder {
  color: #94a3b8;
}

.search-bar button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  border: none;
  background: #3b82f6;
  color: #fff;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.3s ease, transform 0.2s ease;
}

.search-bar button:hover {
  background: #1e40af;
  transform: translateY(-2px);
}

.search-bar button:active {
  transform: translateY(0);
}

.auth-buttons {
  display: flex;
  gap: 12px;
  align-items: center;
}

.auth-buttons button {
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.auth-buttons .login {
  background: transparent;
  border: 2px solid #3b82f6;
  color: #3b82f6;
}

.auth-buttons .login:hover {
  background: #3b82f6;
  color: #fff;
}

.auth-buttons .register {
  background: #3b82f6;
  border: none;
  color: #fff;
}

.auth-buttons .register:hover {
  background: #1e40af;
  transform: translateY(-2px);
}

.auth-buttons .register:active {
  transform: translateY(0);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.welcome {
  font-size: 16px;
  color: #1e40af;
  font-weight: 500;
}

.logout {
  background: #ef4444;
  border: none;
  color: #fff;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.logout:hover {
  background: #dc2626;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    padding: 12px 16px;
    flex-wrap: wrap;
    gap: 12px;
  }

  .search-bar {
    margin: 12px 0;
    max-width: 100%;
  }

  .auth-buttons {
    gap: 8px;
  }

  .user-info {
    flex-direction: column;
    gap: 8px;
  }
}

@media (max-width: 480px) {
  .logo {
    font-size: 20px;
  }

  .logo img {
    width: 32px;
    height: 32px;
  }

  .search-bar input {
    font-size: 14px;
    padding: 10px 12px;
  }

  .search-bar button {
    padding: 10px 16px;
    font-size: 14px;
  }
}

.dropdown-menu {
  position: absolute;
  right: 0;
  top: 48px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 24px 0 rgba(120, 160, 255, 0.13);
  border: 1px solid #e3eaf5;
  min-width: 120px;
  z-index: 100;
  padding: 8px 0;
}

.menu-item {
  padding: 10px 20px;
  color: #2563eb;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.15s;
}

.menu-item:hover {
  background: #e3edfa;
}
</style>
